package com.zx.mobile.controller;

import com.zx.map.service.*;
import com.zx.map.service.model.BaseAcctInfoModel;
import com.zx.map.service.model.CreditRepayInfoModel;
import com.zx.map.service.model.CreditRepayLogModel;
import com.zx.map.service.model.CreditRepayResponse;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.RiskControlModel;
import com.zx.map.utils.SUConstants;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.PayRateHelper;
import com.zx.mobile.SessionHelper;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.mobile.domain.RepayApplyDomain;
import com.zx.mobile.domain.creditrepay.CreditSelectDomain;
import com.zx.mobile.service.proxy.CreditRepayCommonProxy;
import com.zx.mobile.service.proxy.CreditRepayProxy;
import com.zx.platform.utils.MD5Util;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 15-7-5 Time: 下午8:09 To
 * change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/mobile/index")
public class CreditRepayController {
    /**
     * log
     */
    private static Logger log = Logger.getLogger(CreditRepayController.class);
    @Autowired
    private CreditRepayInfoService creditRepayInfoService;
    @Autowired
    private BaseAcctInfoService baseAcctInfoService;
    @Autowired
    private CreditRepayLogService creditRepayLogService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private RiskControlService riskControlService;

    /**
     * 信用卡还款 首页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/creditRepay")
    public String creditRepay(Model model, HttpServletRequest request) {
        try {
            // 获取session信息
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            //获取最新数据
            MerchantInfoModel currentModel = merchantInfoService.getModelByKey(user.getMerchantInfoDetailModel().getMerchantId());
            //交易密码不为空的情况下  允许用户进行设置密码
            //若交易密码为空 需要用户先设置密码
            if (StringUtils.isNotBlank(currentModel.getTradePassword())) {
                CreditRepayInfoModel param = new CreditRepayInfoModel();
                param.setMerchantId(user.getMerchantInfoDetailModel()
                        .getMerchantId());
                List<CreditRepayInfoModel> creditRepayInfoModels = creditRepayInfoService
                        .getListByModel(param);
                creditRepayInfoModels = CreditRepayProxy
                        .transformCreditRepay(creditRepayInfoModels);
                request.getSession().setAttribute(SessionHelper.CREDITREPAYCARD,
                        creditRepayInfoModels);
                model.addAttribute("list", creditRepayInfoModels);
                return "/jsp/mobile/creditrepay/repayindex";
            } else {
                model.addAttribute("operatorType", MobileCommonHelper.URLRETURN_CREDIT);//设置交易密码 回退到修改交易密码
                return "/jsp/mobile/pwd/setpaypwd";
            }
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 信用卡还款 添加信用卡前置
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/addCreditCardPre")
    public String addCreditCardPre(CreditSelectDomain creditSelectDomain,
                                   Model model, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(creditSelectDomain.getNotifyDate())) {
                creditSelectDomain.setNotifyDate("1");  //默认每月第一天
            }
            model.addAttribute("model", creditSelectDomain);
            return "/jsp/mobile/creditrepay/addcreditcard";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 信用卡还款 添加信用卡
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/addCreditCard")
    @ResponseBody
    public CreditSelectDomain addCreditCard(
            CreditSelectDomain creditSelectDomain, Model model,
            HttpServletRequest request) {
        try {
            // 获取session信息
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            CreditRepayInfoModel creditModel = CreditRepayProxy
                    .transformToCreditRepay(user, creditSelectDomain);
            creditRepayInfoService.add(creditModel);
            creditSelectDomain.setMsg("新增成功");
            creditSelectDomain.setSuccess(true);
        } catch (Exception e) {
            log.error("系统异常", e);
            creditSelectDomain.setMsg("添加信用卡失败" + e.getMessage());
            creditSelectDomain.setSuccess(false);
        }
        return creditSelectDomain;
    }

    /**
     * 信用卡还款 首页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/manageCreditCardPre")
    public String manageCreditCardPre(Model model, HttpServletRequest request) {
        try {
            // 获取session信息
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            CreditRepayInfoModel param = new CreditRepayInfoModel();
            param.setMerchantId(user.getMerchantInfoDetailModel()
                    .getMerchantId());
            List<CreditRepayInfoModel> creditRepayInfoModels = creditRepayInfoService
                    .getListByModel(param);
            creditRepayInfoModels = CreditRepayProxy
                    .transformCreditRepay(creditRepayInfoModels);
            model.addAttribute("list", creditRepayInfoModels);
            return "/jsp/mobile/creditrepay/manageCreditCardPre";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 信用卡管理  add by wenjw 2016.1.28
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/manageCreditCard")
    public String manageCreditCard(CreditSelectDomain creditSelectDomain,
                                   Model model, HttpServletRequest request) {
        try {
            CreditRepayInfoModel creditRepayInfoModel = creditRepayInfoService.getModelByKey(creditSelectDomain.getPaycardId());
            if (StrUtils.isEmpty(creditSelectDomain.getBankCode())) {
                creditSelectDomain.setBankCode(creditRepayInfoModel.getBankCode());
            }
            if (StrUtils.isEmpty(creditSelectDomain.getBankName())) {
                creditSelectDomain.setBankName(creditRepayInfoModel.getBankName());
            }
            if (StrUtils.isEmpty(creditSelectDomain.getCardName())) {
                creditSelectDomain.setCardName(creditRepayInfoModel.getCardName());
            }
            if (StrUtils.isEmpty(creditSelectDomain.getNotifyFlag())) {
                creditSelectDomain.setNotifyFlag(creditRepayInfoModel.getNotifyFlag());
            }
            if (StrUtils.isEmpty(creditSelectDomain.getNotifyDate())) {
                creditSelectDomain.setNotifyDate(creditRepayInfoModel.getNotifyDate());
            }
            if (StrUtils.isEmpty(creditSelectDomain.getCardNo())) {
                creditSelectDomain.setCardNo(creditRepayInfoModel.getBankAccount());
            }
            model.addAttribute("model", creditSelectDomain);
            return "/jsp/mobile/creditrepay/manageCreditCard";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 修改信用卡信息
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/manageCreditCardEdit")
    @ResponseBody
    public CreditSelectDomain manageCreditCardEdit(
            CreditSelectDomain creditSelectDomain, Model model,
            HttpServletRequest request) {
        try {
            // 获取session信息
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            /*CreditRepayInfoModel creditModel = CreditRepayProxy
                    .transformToCreditRepay(user, creditSelectDomain);*/
            CreditRepayInfoModel creditModel = creditRepayInfoService.getModelByKey(creditSelectDomain.getPaycardId());
            creditModel.setBankCode(creditSelectDomain.getBankCode());
            creditModel.setBankName(creditSelectDomain.getBankName());
            creditModel.setCardName(creditSelectDomain.getCardName());
            creditModel.setNotifyFlag(creditSelectDomain.getNotifyFlag());
            creditModel.setNotifyDate(creditSelectDomain.getNotifyDate());
            creditModel.setBankAccount(creditSelectDomain.getCardNo());
            creditRepayInfoService.update(creditModel);
            creditSelectDomain.setMsg("修改成功");
            creditSelectDomain.setSuccess(true);
        } catch (Exception e) {
            log.error("系统异常", e);
            creditSelectDomain.setMsg("修改信用卡失败" + e.getMessage());
            creditSelectDomain.setSuccess(false);
        }
        return creditSelectDomain;
    }


    /**
     * 信用卡还款 添加信用卡--还款日期
     *
     * @param creditSelectDomain
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/supportNotifyDayList")
    public String supportNotifyDayList(CreditSelectDomain creditSelectDomain, Model model, HttpServletRequest request) {
        try {
            model.addAttribute("model", creditSelectDomain);
            return "/jsp/mobile/creditrepay/supportnotifydaylist";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 信用卡还款 添加信用卡--支持信用卡列表
     *
     * @param creditSelectDomain
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/supportCreditList")
    public String supportCreditList(CreditSelectDomain creditSelectDomain, Model model, HttpServletRequest request) {
        try {
            model.addAttribute("model", creditSelectDomain);
            return "/jsp/mobile/creditrepay/supportcreditlist";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 信用卡还款 交易
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/repayTradePre")
    public String repayTradePre(CreditSelectDomain creditSelectDomain,
                                Model model, HttpServletRequest request) {
        try {
            // 获取session信息
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            List<CreditRepayInfoModel> list = (List<CreditRepayInfoModel>) request
                    .getSession().getAttribute(SessionHelper.CREDITREPAYCARD);
            for (CreditRepayInfoModel temp : list) {
                if (temp.getBankAccount()
                        .equals(creditSelectDomain.getCardNo())) {
                    model.addAttribute("payCard", temp);
                    model.addAttribute("model", creditSelectDomain);
                    // 获取账户信息
                    BaseAcctInfoModel acctInfo = baseAcctInfoService
                            .getModelByKey(user.getMerchantInfoDetailModel()
                                    .getMerchantId());
                    model.addAttribute("acct", acctInfo);
                    model.addAttribute("rate", PayRateHelper.CREDITREPAYRATE);
                    request.getSession().setAttribute(SessionHelper.CREDITREPAYCARDONE,
                            temp);
                    return "/jsp/mobile/creditrepay/repaycard";
                }
            }
            model.addAttribute("errorMsg", "信用卡还款异常");
            return "/jsp/mobile/error";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 信用卡还款结果页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/repayresult")
    public String repayresult(RepayApplyDomain repayApplyDomain, Model model,
                              HttpServletRequest request) {
        try {
            log.debug("信用卡交易："
                    + ToStringBuilder.reflectionToString(repayApplyDomain));
            // 验证交易密码是否正确
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            //事中风控 对交易金额进行限制
            RiskControlModel riskControlModel = riskControlService.bussinessAmtRiskControl(SUConstants.TRANSTYPE_CREDITENCASH, repayApplyDomain.getRepayAmt(), user.getMerchantInfoDetailModel());
            if (MobileCommonHelper.RISKPASSCODE.equals(riskControlModel.getRiskCode())) {//如果风控通过交易限额
                String tradePwd = PmpUtils.encoderByMD5(MD5Util
                        .getMD5Str(repayApplyDomain.getTradePwd()));
                //获取最新数据
                MerchantInfoModel currentModel = merchantInfoService.getModelByKey(user.getMerchantInfoDetailModel().getMerchantId());
                if (!tradePwd.equals(currentModel.getTradePassword())) {
                    log.info("信用卡还款失败，交易密码错误");
                    model.addAttribute("errorMsg", "交易密码错误");
                    return "/jsp/mobile/error";
                } else {
                    BaseAcctInfoModel temp = baseAcctInfoService.getModelByKey(user
                            .getMerchantInfoDetailModel().getMerchantId());
                    if (temp.getAvlBal() >= Double.parseDouble(repayApplyDomain
                            .getTradeAmt())) {
                        // 信用卡还款 记录操作流水
                        CreditRepayLogModel param = CreditRepayCommonProxy
                                .transformCreditRepayLog(user, repayApplyDomain);
                        CreditRepayInfoModel creditOne = (CreditRepayInfoModel) request.getSession().getAttribute(SessionHelper.CREDITREPAYCARDONE);
                        param.setBankAccount(creditOne.getBankAccount());
                        param.setBankCode(creditOne.getBankCode());
                        // 结算
                        CreditRepayResponse creditRepayResponse = creditRepayLogService
                                .dealCreditRepay(param, creditOne);
                        log.info("信用卡还款返回 :" + ToStringBuilder.reflectionToString(creditRepayResponse));
                        if ("0000".equals(creditRepayResponse.getReturnCode())) {
                            model.addAttribute("model", creditOne);
                            model.addAttribute("domain", repayApplyDomain);
                            return "/jsp/mobile/creditrepay/repayresult";
                        }
                        model.addAttribute("errorMsg", "信用卡还款出错了");
                        return "/jsp/mobile/error";
                    } else {
                        log.info("信用卡还款可用余额不够");
                        model.addAttribute("errorMsg", "信用卡还款超过可用余额");
                        return "/jsp/mobile/error";
                    }
                }

            } else {
                model.addAttribute("errorMsg", riskControlModel.getRiskMsg());
                log.error("未通过系统风控" + riskControlModel.getRiskMsg());
                return "/jsp/mobile/error";
            }
        } catch (Exception e) {
            model.addAttribute("errorMsg", e.getMessage());
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 刷卡支付限额表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/cardpaylimit")
    public String cardpaylimit(Model model, HttpServletRequest request) {
        try {
            return "/jsp/mobile/creditrepay/cardpaylimit";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * @return
     */
    @RequestMapping("/delete")
    public
    @ResponseBody
    CreditSelectDomain delete(CreditRepayInfoModel model) {
        CreditSelectDomain creditSelectDomain = new CreditSelectDomain();
        try {
            creditRepayInfoService.delete(model);
            creditSelectDomain.setSuccess(true);
            creditSelectDomain.setMsg("删除信息成功");
            log.debug("删除信息成功");
        } catch (Exception e) {
            creditSelectDomain.setSuccess(false);
            creditSelectDomain.setMsg("删除信息失败");
            log.error("删除信息失败" + e.getMessage(), e);
        }
        return creditSelectDomain;
    }

    /**
     * 信用卡 账单
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/repayTradeList")
    public String repayTradeList(Model model, HttpServletRequest request) {
        try {
            // 获取session信息
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            CreditRepayLogModel param = new CreditRepayLogModel();
            param.setMerchantId(user.getMerchantInfoDetailModel()
                    .getMerchantId());

            List<CreditRepayLogModel> creditRepayLogModels = creditRepayLogService
                    .getListByModel(param);
            Map<String, List> mapList = CreditRepayProxy
                    .transformCreditRepayLog(creditRepayLogModels);
            request.getSession().setAttribute(SessionHelper.CREDITREPAYLOG,
                    creditRepayLogModels);
            model.addAttribute("mapList", mapList);
            return "/jsp/mobile/creditrepay/repayTradeList";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }
}
